import React from 'react';
import { PageContainer } from '@/molecules';
import { withRouter } from 'umi';
import { Button, Divider, Empty, message, Skeleton } from 'antd';
import useDynamicList from '@/hooks/useDynamicList';
import { useRequest } from '@/hooks';
import {
    queryEmployeeCareList,
    saveEmployeeCare,
    updateEmployeeCare
} from '@/pages/Organization/EmployeeManage/services';
import EmployeeCareForm from '@/pages/Organization/EmployeeManage/EmployeeCare/components/EmployeeCareForm';
import EmployeeCardSimple from '../components/EmployeeCard/EmployeeCardSimple';

/**
 * 员工关怀
 */
const EmployeeCare = ({ location }) => {
    const userInfo = JSON.parse(localStorage.getItem('user'));
    const { employeeCode } = location.query;
    const isPersonalPage = userInfo.employeeCode === employeeCode; // 是否是个人

    // 列表管理
    const {
        list: careList,
        unshift: careListUnshift,
        remove: careListRemove,
        replace: careListReplace,
        getKey: careListGetKey,
        resetList: careListReset
    } = useDynamicList([]);

    // 添加新记录
    const handleAddCareItem = () => {
        careListUnshift({
            careStarterName: userInfo.employeeName,
            careStarterCode: userInfo.employeeCode,
            caredEmployeeCode: employeeCode,
            type: 3
        });
    };

    // 获取数据
    const { loading: fetchCareDataLoading } = useRequest(
        () => queryEmployeeCareList({ caredEmployeeCode: employeeCode }),
        {
            refreshDeps: [employeeCode],
            onSuccess: res => {
                if (res) {
                    const { code, msg, data } = res;
                    if (code === 10000) {
                        if (data.length === 0 && !isPersonalPage) {
                            handleAddCareItem();
                        } else {
                            careListReset(data?.reverse());
                        }
                    } else {
                        message.error(msg);
                    }
                }
            }
        }
    );

    // 提交
    const { run: submitRun } = useRequest(
        formData => (formData.id ? updateEmployeeCare(formData) : saveEmployeeCare(formData)),
        {
            manual: true
        }
    );

    // 保存
    const handleSubmit = async (values, form, index) => {
        // 提交
        const res = await submitRun(values);
        if (res.code === 10000) {
            const returnData = { ...values, ...res.data };
            careListReplace(index, returnData);
            message.success(res.msg);
        } else {
            message.error(res.msg);
        }
    };

    // 取消编辑
    const handleCancel = (item, index) => {
        if (!item.id) {
            careListRemove(index);
        }
    };

    // 判断是否有编辑的权限
    const handleHasEditAuth = item => {
        // 只有自己新增的可以修改
        if (item.careStarterCode === userInfo.employeeCode) {
            return true;
        }
        // 当前时间小于关怀时间的
        // if (new Date(item.startDate).getTime() > new Date(moment(new Date()).format('YYYY-MM-DD 00:00:00')).getTime()) {
        //     return true;
        // }
        // 有编辑权限的?
        return false;
    };

    // render
    return (
        <PageContainer>
            {/* 员工基础信息 */}
            <EmployeeCardSimple employeeCode={employeeCode}/>
            {employeeCode && (
                <>
                    <Divider style={{ margin: '16px 0' }} />
                    <Skeleton loading={fetchCareDataLoading}>
                        {/* 控制一次只能同时新增一条记录 */}
                        {!isPersonalPage && careList.filter(item => !item.id).length === 0 && (
                            <Button type="dashed" icon="plus" style={{ margin: '10px 0' }} block onClick={handleAddCareItem}>
                                添加员工关怀
                            </Button>
                        )}
                        {careList.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                        {!!careList.length &&
                            careList.map((item, index) => (
                                <EmployeeCareForm
                                    key={careListGetKey(index)}
                                    hasEditAuth={handleHasEditAuth(item)}
                                    formData={item}
                                    index={index}
                                    careListLength={careList.length}
                                    onSubmit={(values, form) => handleSubmit(values, form, index)}
                                    onCancel={() => handleCancel(item, index)}
                                />
                            ))}
                    </Skeleton>
                </>
            )}
        </PageContainer>
    );
};

export default withRouter(EmployeeCare);
